<template>
  <div class="logs-management">
    <!-- 查询表单 -->
    <v-card class="mb-4 " elevation="10" rounded="lg">
      <v-card-title>
        <v-icon left>mdi-account-key</v-icon>
        登录日志管理
      </v-card-title>
      <v-card-text>
        <v-form @submit.prevent="handleQuery">
          <v-row>
            <v-col cols="12" md="2">
              <v-btn-toggle v-model="queryForm.type_EQ" mandatory color="primary" class="mb-2">
                <v-btn value="1">登入</v-btn>
                <v-btn value="2">登出</v-btn>
              </v-btn-toggle>
            </v-col>
            <v-col cols="12" md="2">
              <v-text-field v-model="queryForm.username_EQ" label="用户名" clearable variant="outlined"
                density="compact" />
            </v-col>
            <v-col cols="12" md="2">
              <v-text-field v-model="queryForm.realName_LIKE" label="用户昵称" clearable variant="outlined"
                density="compact" />
            </v-col>
            <v-col cols="12" md="4">
              <v-row>
                <v-col cols="6">
                  <v-text-field v-model="dateRange.start" label="开始时间" type="datetime-local" variant="outlined"
                    density="compact" />
                </v-col>
                <v-col cols="6">
                  <v-text-field v-model="dateRange.end" label="结束时间" type="datetime-local" variant="outlined"
                    density="compact" />
                </v-col>
              </v-row>
            </v-col>
            <v-col cols="12" md="2" class="d-flex align-center">
              <v-btn type="submit" color="primary" :loading="loading" prepend-icon="mdi-magnify" class="mr-2">
                查询
              </v-btn>
              <v-btn color="secondary" variant="outlined" @click="handleReset" prepend-icon="mdi-refresh" class="mr-2">
                重置
              </v-btn>
              <v-menu>
                <template #activator="{ props }">
                  <v-btn color="success" variant="outlined" v-bind="props" prepend-icon="mdi-download"
                    :disabled="list.length === 0">
                    导出
                  </v-btn>
                </template>
                <v-list>
                  <v-list-item @click="handleExport('csv')">
                    <v-list-item-title>
                      <v-icon left>mdi-file-delimited</v-icon>
                      导出CSV
                    </v-list-item-title>
                  </v-list-item>
                  <v-list-item @click="handleExport('excel')">
                    <v-list-item-title>
                      <v-icon left>mdi-file-excel</v-icon>
                      导出Excel
                    </v-list-item-title>
                  </v-list-item>
                  <v-list-item @click="handleExport('json')">
                    <v-list-item-title>
                      <v-icon left>mdi-code-json</v-icon>
                      导出JSON
                    </v-list-item-title>
                  </v-list-item>
                </v-list>
              </v-menu>
            </v-col>
          </v-row>
          <!-- 快捷时间选择 -->
          <v-row>
            <v-col cols="12">
              <v-chip-group>
                <v-chip v-for="shortcut in timeShortcuts" :key="shortcut.text" @click="handleTimeShortcut(shortcut)"
                  variant="outlined" size="small">
                  {{ shortcut.text }}
                </v-chip>
              </v-chip-group>
            </v-col>
          </v-row>
        </v-form>
      </v-card-text>
    </v-card>
    <!-- 数据表格 -->
    <v-card elevation="10" rounded="lg">
      <v-data-table v-model:page="queryForm.pageNo" v-model:items-per-page="queryForm.pageSize" :headers="headers"
        :items="list" :loading="loading" :items-length="total" :items-per-page-options="[10, 20, 50, 100]"
        loading-text="正在加载..." no-data-text="暂无数据" @update:page="handlePageChange"
        @update:items-per-page="handleSizeChange">
        <!-- 序号列 -->
        <template #item.index="{ index }">
          {{ (queryForm.pageNo - 1) * queryForm.pageSize + index + 1 }}
        </template>
        <!-- 来源字典列 -->
        <template #item.loginFrom="{ item }">
          <v-chip color="info" size="small" variant="flat">
            {{ getLoginFromName(item.loginFrom) }}
          </v-chip>
        </template>
        <!-- 用户代理列 -->
        <template #item.userAgent="{ item }">
          <div class="text-truncate" style="max-width: 150px;">
            {{ item.userAgent }}
          </div>
          <v-tooltip v-if="item.userAgent && item.userAgent.length > 30" activator="parent" location="top">
            {{ item.userAgent }}
          </v-tooltip>
        </template>
        <!-- 创建时间列 -->
        <template #item.createTime="{ item }">
          {{ formatDateTime(item.createTime) }}
        </template>
      </v-data-table>
    </v-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { getList } from '@/api/system/logs/loginLogsManagement'
import { useMessage } from '@/composables/useMessage'
import { exportData, formatDateTimeForExport, type ExportFormat } from '@/utils/export'
import { useDict } from '@/composables/useDict'
import type { DictItem } from '@/utils/dict'

// 类型定义
interface LogItem {
  id: string
  username: string
  realName: string
  remoteAddr: string
  loginFrom: string
  userAgent: string
  createTime: string
}

interface QueryForm {
  pageNo: number
  pageSize: number
  type_EQ: string
  username_EQ: string
  realName_LIKE: string
  createTime_BEGIN: string
  createTime_END: string
}

interface TimeShortcut {
  text: string
  days: number
}

const { show: showMessage } = useMessage()
const loading = ref(false)
const list = ref<LogItem[]>([])
const total = ref(0)

// 查询表单
const queryForm = reactive<QueryForm>({
  pageNo: 1,
  pageSize: 10,
  type_EQ: '1',
  username_EQ: '',
  realName_LIKE: '',
  createTime_BEGIN: '',
  createTime_END: ''
})

// 日期范围
const dateRange = reactive({
  start: '',
  end: ''
})

// 来源字典
const { getDictList } = useDict()
const loginFromDict = ref<DictItem[]>([])

const getLoginFromName = (val: string) => {
  const found = loginFromDict.value.find(item => item.dictValue === val)
  return found ? found.dictName : val
}

// 时间快捷选择
const timeShortcuts: TimeShortcut[] = [
  { text: '最近一周', days: 7 },
  { text: '最近一个月', days: 30 },
  { text: '最近三个月', days: 90 }
]

// 表格列配置
const headers = [
  { title: '序号', key: 'index', width: 80, sortable: false },
  { title: '用户名', key: 'username', width: 120, sortable: false },
  { title: '用户姓名', key: 'realName', width: 180, sortable: false },
  { title: '用户IP', key: 'remoteAddr', width: 150, sortable: false },
  { title: '登陆来源', key: 'loginFrom', width: 120, sortable: false },
  { title: '用户代理', key: 'userAgent', width: 180, sortable: false },
  { title: '创建时间', key: 'createTime', width: 180, sortable: false }
]

// 格式化日期时间
const formatDateTime = (dateTime: string): string => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 处理时间快捷选择
const handleTimeShortcut = (shortcut: TimeShortcut) => {
  const end = new Date()
  const start = new Date()
  start.setTime(start.getTime() - shortcut.days * 24 * 60 * 60 * 1000)
  dateRange.start = start.toISOString().slice(0, 16)
  dateRange.end = end.toISOString().slice(0, 16)
}

// 查询数据
const handleQuery = () => {
  if (dateRange.start) {
    queryForm.createTime_BEGIN = new Date(dateRange.start).toISOString().replace('T', ' ').slice(0, 19)
  } else {
    queryForm.createTime_BEGIN = ''
  }
  if (dateRange.end) {
    queryForm.createTime_END = new Date(dateRange.end).toISOString().replace('T', ' ').slice(0, 19)
  } else {
    queryForm.createTime_END = ''
  }
  queryForm.pageNo = 1
  fetchData()
}

// 重置查询
const handleReset = () => {
  queryForm.type_EQ = '1'
  queryForm.username_EQ = ''
  queryForm.realName_LIKE = ''
  queryForm.createTime_BEGIN = ''
  queryForm.createTime_END = ''
  dateRange.start = ''
  dateRange.end = ''
  queryForm.pageNo = 1
  fetchData()
}

// 页码变化
const handlePageChange = (page: number) => {
  queryForm.pageNo = page
  fetchData()
}

// 页大小变化
const handleSizeChange = (size: number) => {
  queryForm.pageSize = size
  queryForm.pageNo = 1
  fetchData()
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const { data } = await getList(queryForm)
    if (data) {
      list.value = data.rows || []
      total.value = data.total || 0
    }
  } catch (error) {
    console.error('获取登录日志数据失败:', error)
    showMessage('获取登录日志数据失败', 'error')
  } finally {
    loading.value = false
  }
}

// 导出数据
const handleExport = (format: ExportFormat) => {
  try {
    if (list.value.length === 0) {
      showMessage('没有可导出的数据', 'warning')
      return
    }
    const exportList = list.value.map(item => ({
      ...item,
      loginFrom: getLoginFromName(item.loginFrom),
      createTime: formatDateTimeForExport(item.createTime)
    }))
    const timestamp = new Date().toISOString().slice(0, 19).replace(/[:-]/g, '')
    const filename = `登录日志_${timestamp}`
    exportData(exportList, {
      filename,
      format,
      fields: ['username', 'realName', 'remoteAddr', 'loginFrom', 'userAgent', 'createTime'],
      headers: ['用户名', '用户姓名', '用户IP', '登陆来源', '用户代理', '创建时间']
    })
    showMessage(`${format.toUpperCase()}文件导出成功`, 'success')
  } catch (error) {
    console.error('导出失败:', error)
    showMessage('导出失败', 'error')
  }
}

onMounted(async () => {
  loginFromDict.value = await getDictList('login_from')
  fetchData()
})
</script>

<style scoped>
.logs-management {
  padding: 16px;
}

.text-truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
